package my.springboot3.controller;

import jakarta.servlet.http.HttpServletRequest;
import my.springboot3.dto.Respond;
import my.springboot3.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@Controller
public class FileController {
    @Autowired
    private ArticleService articleService;



    /**
     * 文章封面图片上传
     */
    @PostMapping("/upload")
    public Respond<String> upload(MultipartFile file) {
        // 获取上传图片的URL
        String url = articleService.upload(file);
        return Respond.success(url);
    }

    /**
     * 图片保存文件夹路径
     */
    @Value("${app.upload.directory}")
    private String uploadPath;
    /**
     * 图片回显
     */
    @GetMapping("/image/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename, HttpServletRequest request) {
        System.out.println(request.getRequestURI());
        try {
            // 获取图片的访问地址
            Path file = Paths.get(uploadPath).resolve(filename);
            // 创建Resource对象,访问图片
            Resource resource = new FileSystemResource(file);

            if (resource.exists() || resource.isReadable()) {
                // 如果图片存在且可读，则返回ResponseEntity对象
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG) // 根据实际情况调整MediaType
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }





}